<?php
require_once("global.inc");

class News
{

    function getNews($id){
        $query = "SELECT * FROM news WHERE id = '$id'";
        $db = $this->_getDB();
        $result = $db->query($query);
        return $result->fetchArray();
    }

    function addNews($title,$content){
        $current_date = date("Y-m-d H:i:s");

        $query = "INSERT INTO news (
                [create_date]
               ,[edit_date]
               ,[title]
               ,[content]
            ) VALUES (
                '$current_date',
                '$current_date',
                '$title',
                '$content'
            )";
        trace($query,"add news query");

        $db = $this->_getDB();
        $db->exec($query);
    }

    function updateNews($id,$title,$content){
        $edit_date = date("Y-m-d H:i:s");;
        $query = "UPDATE news SET edit_date = '$edit_date', title = '$title', content = '$content' WHERE id = '$id'";
        $db = $this->_getDB();
        $db->exec($query);
    }



    var $db;
    private function _getDB()
    {
        if (!$this->db)
        {
            global $EB_SQLITE_FILENAME;
            $this->db = new SQLite3($EB_SQLITE_FILENAME);
            $this->db->exec(
                "CREATE TABLE IF NOT EXISTS news (
                [id] INTEGER PRIMARY KEY,
	            [create_date] [datetime] NOT NULL,
	            [edit_date] [datetime] NOT NULL,
	            [title] [varchar](255) NOT NULL,
	            [content] [text] NOT NULL )
	            ");
        }
        return $this->db;
    }


    function getAllNews(){
        $query = "SELECT * FROM news ORDER BY create_date DESC";
        $db = $this->_getDB();
        return $db->query($query);
    }

    function getPageNews($count,$pageNum){
        $offset = ($pageNum-1)*$count;

        $query = "SELECT * FROM news ORDER BY create_date DESC  LIMIT $count OFFSET $offset ";
        $db = $this->_getDB();
        return $db->query($query);
    }

    function getPageNewsCount(){
        $query = "SELECT count(*) FROM news";
        $db = $this->_getDB();
        return $db->querySingle($query);
    }


    function deleteNews($id){
        $query = "DELETE FROM news where id = '$id'";
        trace($query,"news DELETE query");

        $db = $this->_getDB();
        $db->exec($query);
    }

}